﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TaoNiuOA.Models;
using PagedList;

namespace TaoNiuOA.Web.Controllers
{
    public class TaskController : Controller
    {
        private DbEntity db = new DbEntity();

        //分页记录数据
        int pageSize = 20;

        //任务列表
        public ViewResult Index(int? page)
        {
            var index = (page ?? 1) - 1;
            var mod = Request.QueryString["mod"];
            ViewBag.mod = mod;

            //默认,所有任务
            var list = db.Tasks.OrderByDescending(n => n.PubTime).ThenBy(n => n.Level).ToPagedList(index, pageSize);
            switch (mod)
            {
                //未被领取
                case "notTake":
                    list = db.Tasks.Where(n => n.Status == 0).OrderByDescending(n => n.PubTime).ThenBy(n => n.Level).ToPagedList(index, pageSize);
                    break;
                //已被领取
                case "take":
                    list = db.Tasks.Where(n => n.Status == 1).OrderByDescending(n => n.PubTime).ThenBy(n => n.Level).ToPagedList(index, pageSize);
                    break;
                //执行中的
                case "executing":
                    list = db.Tasks.Where(n => n.Status == 2).OrderByDescending(n => n.PubTime).ThenBy(n => n.Level).ToPagedList(index, pageSize);
                    break;
                //已完成的
                case "finish":
                    list = db.Tasks.Where(n => n.Status == 3).OrderByDescending(n => n.PubTime).ThenBy(n => n.Level).ToPagedList(index, pageSize);
                    break;
                //默认,所有任务
                default:
                    break;
            }
            return View(list);
        }

        //显示已完成任务,用于审批
        public ViewResult Approve(int? page)
        {
            var index = (page ?? 1) - 1;
            var mod = Request.QueryString["mod"];
            ViewBag.mod = mod;

            //默认,所有已完成的任务且未审批的任务
            var list = db.Tasks.Where(n => n.Status == 3 && n.IsGood == null).ToPagedList(index, pageSize);

            return View(list);
        }

        //显示审批任务选项
        [IsAdmin]
        [HttpPost]
        public ActionResult ShowApproveTask(int id)
        {
            var user = Session["users"] as TaoNiuOA.Models.User;
            Task task = db.Tasks.SingleOrDefault(n => n.TaskID == id);
            var strHtml = new System.Text.StringBuilder();
            if (task == null)
                return Json("找不到记录");

            //显示审批
            if (task.IsGood == null)
            {
                strHtml = new System.Text.StringBuilder();
                strHtml.Append("<div>应得绩效:" + task.Point + "</div>");
                strHtml.Append(string.Format("<div>给予绩效:<input type='text' value='{0}' id='taskPoint' style='width:40px;'/></div>", task.Point));
                strHtml.Append("<div>是否<select id='IsGood'>");
                strHtml.Append("<option value='true' selected='selected'>合格</option>");
                strHtml.Append("<option value='false'>不合格</option>");
                strHtml.Append("</select>");
                strHtml.Append("<div>备注:<textarea id='remark'></textarea></div>");
            }
            else if (task.IsGood == true)
                return Json("任务已审批为合格,无须再审批");

            else
            {
                return Json("暂无操作");
            }
            return Json(strHtml.ToString());
        }

        //审批任务
        [IsAdmin]
        [HttpPost]
        public ActionResult ApproveTask()
        {
            try
            {
                var IsGood = Convert.ToBoolean(Request.QueryString["IsGood"]);
                var taskID = Convert.ToInt32(Request.QueryString["taskID"]);
                var point = Convert.ToInt32(Request.QueryString["taskPoint"]);
                var remark = Request.QueryString["remark"];

                var user = Session["users"] as TaoNiuOA.Models.User;
                Task task = db.Tasks.SingleOrDefault(n => n.TaskID == taskID);
                if (task == null)
                    return Json("error");

                //合格
                if (IsGood)
                {
                    using (var ts = new System.Transactions.TransactionScope())
                    {
                        db.Entry(task).State = EntityState.Modified;
                        task.IsGood = true;
                        //task.Point = point;
                        task.Remark = remark;
                        task.ApproveID = user.UserID;
                        task.LastUpdate = DateTime.Now;

                        //给任务执行者绩效
                        var performance = new Performance();
                        performance.LastUpdate = DateTime.Now;
                        performance.Month = DateTime.Now.ToString("yyyy-MM");
                        performance.TotalPoint = task.Point;
                        performance.PayPoint = point;
                        performance.UserID = Convert.ToInt32(task.UserID);
                        performance.Status = 1;
                        performance.Title = task.Name;
                        db.Performances.Add(performance);

                        db.SaveChanges();
                        ts.Complete();
                        return Json("ok");
                    }
                }

                //不合格,把任务退回去
                else
                {
                    db.Entry(task).State = EntityState.Modified;
                    task.LastUpdate = DateTime.Now;
                    task.Status = 2;
                    db.SaveChanges();
                    return Json("ok");
                }
            }
            catch
            {
                return Json("error");
            }
        }

        [IsAdmin]
        public ViewResult Details(int id)
        {
            Task task = db.Tasks.Find(id);
            //显示任务评级
            var isg = "还未评级";
            if (task.Status == 3)
            {
                if (task.IsGood != null)
                {
                    if (Convert.ToBoolean(task.IsGood))
                        isg = "合格";
                    else
                        isg = "不合格";
                }
            }
            ViewBag.IsGood = isg;
            return View(task);
        }

        [IsAdmin]
        public ActionResult Create()
        {
            TaskType(0);
            return View();
        }

        [IsAdmin]
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(Task task, FormCollection fc)
        {
            TaskType(0);
            var content = fc["content"];

            task.Content = content;
            task.Status = 0;
            task.PubTime = DateTime.Now;
            task.LastUpdate = DateTime.Now;
            db.Tasks.Add(task);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        [IsAdmin]
        public ActionResult Edit(int id)
        {
            Task task = db.Tasks.SingleOrDefault(n => n.TaskID == id);
            TaskType(id);
            return View(task);
        }

        /// <summary>
        /// 初始化任务类型,0为没有默认值
        /// //id:任务ID:TaskID,区别TaskTypeID
        /// </summary>
        /// <param name="id"></param>
        private void TaskType(int id)
        {
            if (id == 0)
            {
                ViewBag.TaskTypeID = new SelectList(db.TaskTypes.OrderBy(n => n.Sort), "TaskTypeID", "TypeName");
            }
            else
            {
                var taskTypes = db.TaskTypes;
                var task = db.Tasks.SingleOrDefault(n => n.TaskID == id);
                ViewBag.TaskTypeID = new SelectList(taskTypes.OrderBy(n => n.Sort), "TaskTypeID", "TypeName", task.TaskTypeID);
            }
        }


        [IsAdmin]
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(Task task)
        {
            TaskType(0);
            db.Entry(task).State = EntityState.Modified;
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        //领取任务
        [IsLogon]
        [HttpPost]
        public ActionResult TakeTask()
        {
            Response.ContentType = "application/json";
            var taskid = Request.QueryString["id"];
            if (!ShenLan.Common.IntHandler.IsNotNullOrInt(taskid))
            {
                return Json("错误的id");
            }
            
            var id = Convert.ToInt32(taskid);
            var task = db.Tasks.SingleOrDefault(n => n.TaskID == id);
            if (task == null)
                return Json("找不到记录");
            //判断是否已经被领取
            if (task.Status != 0)
                return Json("该任务已经被领取");
            var u = Session["users"] as TaoNiuOA.Models.User;
            db.Entry(task).State = EntityState.Modified;
            task.UserID = u.UserID;
            //把任务状态改为1,即已被领取
            task.Status = 1;
            db.SaveChanges();
            return Json("领取任务成功");
        }



        //删除任务
        [IsAdmin]
        [HttpPost]
        public ActionResult DelTask(int id)
        {
            try
            {
                Task task = db.Tasks.Find(id);
                if (task.Status == 2 || task.Status == 3)
                    return Json("该任务正在执行中或已经完成,不能删除");
                db.Tasks.Remove(task);
                db.SaveChanges();
                return Json("删除成功");
            }
            catch { return Json("删除失败"); }
        }


        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}